import { Injectable } from '@nestjs/common';
import { Response } from 'src/utils/response';
import { Repository } from 'typeorm';
import { UserService } from 'src/blog/userManager/user.service';
import { beanCopyArray } from 'src/utils';
import { InjectRepository } from '@nestjs/typeorm';
import { TBlogComment } from 'src/entities/blog/comment.entity';
import { CommentAddDto } from './dto/comment-add.dto';
import { CommentListVo } from './vo/comment-list.vo';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(TBlogComment)
    private readonly repository: Repository<TBlogComment>,
    private readonly userService: UserService,
  ) {}

  async addComment(data: Partial<CommentAddDto>) {
    try {
      if (!data.articleId) {
        return Response.error({
          message: 'articleId is required',
        });
      }
      if (!data.content) {
        return Response.error({
          message: 'content is required',
        });
      }
      // 创建评论实体
      const comment = this.repository.create({
        ...data,
        rootId: data.rootId || -1, // 根评论id默认为-1
        toCommentId: data.toCommentId || -1, // 回复的目标评论id默认为-1
        toCommentUserId: data.toCommentUserId || -1, // 回复的目标用户id默认为-1
      });
      await this.repository.save(comment);
      return Response.success({ message: '评论添加成功' });
    } catch (e) {
      return Response.error({ message: e.message });
    }
  }

  //   查询评论列表
  async queryCommentList(articleId: number) {
    try {
      if (!articleId) {
        return Response.error({
          message: 'articleId is required',
        });
      }

      // 获取文章的所有根评论
      const comments = await this.repository.find({
        where: { articleId, rootId: -1 },
      });
      const commentList = await this.handleComments(comments);

      for (const comment of commentList) {
        // 假设 fetchData 是一个返回 Promise 的异步函数
        comment.children = await this.getChildComment(comment.id);
      }

      return Response.success({ data: commentList, message: '查询成功' });
    } catch (e) {
      return Response.error({ message: e.message });
    }
  }

  async getChildComment(id: number) {
    const comments = await this.repository.find({
      where: { rootId: id },
    });
    return await this.handleComments(comments);
  }

  async handleComments(comments: TBlogComment[]) {
    const vo = new CommentListVo();
    const result = beanCopyArray<CommentListVo>(vo, comments);
    const createBys = result.map((v) => v.createdBy);
    const userList = await this.userService.queryUserDetail(createBys);
    const userMap = {};
    userList.forEach((user) => {
      userMap[user.id] = user;
    });
    result.forEach((item) => {
      const userId = item.createdBy;
      const userInfo = userMap[userId];
      item.userName = userInfo.nickName;
      item.userAvatar = userInfo.avatar;
    });

    const commentList = result.filter((item) => item.toCommentUserId != -1);
    if (commentList.length > 0) {
      const createBys = commentList.map((v) => v.toCommentUserId);
      const userList = await this.userService.queryUserDetail(createBys);
      const userMap = {};
      userList.forEach((user) => {
        userMap[user.id] = user;
      });
      commentList.forEach((item) => {
        const userId = item.createdBy;
        const userInfo = userMap[userId];
        item.toCommentUserName = userInfo.nickName;
        item.toCommentUserAvatar = userInfo.avatar;
      });
    }

    return result;
  }
}
